<template>
  <div class="userManager-container">
    <el-container>
      <el-header>
        <span
          style="display: block; width: 100%; height: 30px; background: #001529; text-align: center; font-size: 20px; font-weight: bold; color: white">
          用户数据
        </span>
      </el-header>

      <el-main>
        <div>
          <div style="float: left;margin-bottom: 20px">
            <el-input style="width: 200px" placeholder="查询用户名" v-model="pageUserReq.username"></el-input>
            <el-input style="width: 200px;margin:0 10px" placeholder="查询昵称"
                      v-model="pageUserReq.nickname"></el-input>
            <el-button type="success" @click="sercah(1)">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
          </div>
          <el-card style="width: 100%;">

            <div style="float: right;margin-bottom: 10px">
              <el-button type="success"
                         size="mini"
                         @click="exportData"
                         plain>批量导出
              </el-button>
              <el-upload action="/api/user/import"
                         :headers="{token: user.token}"
                         :on-success="handleImport"
                         style="display: inline-block;margin: 0 10px"
                         :show-file-list="false">
                <el-button type="primary" size="mini" plain>批量导入</el-button>
              </el-upload>
              <el-button type="primary"
                         size="mini"
                         @click="add  = true"
                         plain>新增
              </el-button>
              <el-button type="danger"
                         size="mini"
                         @click="delBatch"
                         plain>批量删除
              </el-button>

              <el-dialog title="编辑" :visible.sync="update">
                <el-form :model="oldUser" :rules="rules2" ref="form">
                  <el-form-item label="用户名" :label-width="formLabelWidth">
                    <el-input v-model="oldUser.username" autocomplete="off"></el-input>
                  </el-form-item>
                </el-form>
                <el-form :model="oldUser">
                  <el-form-item label="昵称" :label-width="formLabelWidth">
                    <el-input v-model="oldUser.nickname" autocomplete="off"></el-input>
                  </el-form-item>

                  <el-form-item label="电子邮箱" :label-width="formLabelWidth">
                    <el-input v-model="oldUser.email" autocomplete="off"></el-input>
                  </el-form-item>

                  <el-form-item label="角色" :label-width="formLabelWidth">
                    <el-input v-model="oldUser.role" autocomplete="off"></el-input>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="update = false">取 消</el-button>
                  <el-button type="primary" @click="handleUpdate">确 定</el-button>
                </div>
              </el-dialog>

              <el-dialog title="新增" :visible.sync="add">
                <el-form :model="newUser" :rules="rules2" ref="form">
                  <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                    <el-input v-model="newUser.username" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="昵称" :label-width="formLabelWidth" prop="nickname">
                    <el-input v-model="newUser.nickname" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="电子邮箱" :label-width="formLabelWidth" prop="email">
                    <el-input v-model="newUser.email" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item label="角色" :label-width="formLabelWidth" prop="role">
                    <el-radio-group v-model="newUser.role">
                      <el-radio label="管理员"></el-radio>
                      <el-radio label="用户"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                  <el-button @click="add = false">取 消</el-button>
                  <el-button type="primary" @click="handleAdd">确 定</el-button>
                </div>
              </el-dialog>
            </div>
            <el-table :data="tableData"
                      style="font-weight: bold;
                      border: #001529;" border
                      v-loading="loading"
                      :header-cell-style="{backgroundColor: 'aliceblue',fontWeight:'bold',color:'#666'}"
                      @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="ID" prop="id" align="center"></el-table-column>
              <el-table-column label="用户名" prop="username" align="center"></el-table-column>
              <el-table-column label="昵称" prop="nickname" align="center"></el-table-column>
              <el-table-column label="电子邮箱" prop="email" align="center"></el-table-column>
              <el-table-column label="角色" prop="role" align="center"></el-table-column>
              <el-table-column label="照片上传" prop="">
                <template v-slot="scope">
                  <el-upload action="/api/file/upload"
                             :headers="{ token: user.token }"
                             :show-file-list="false"
                             :before-upload="beforeFileUpload"
                             :on-success="(row,file) => handleTableFileUpload(scope.row,file)">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" type="el-upload_tip" style="font-size: xx-small; color: red;">
                      只能上传jpg/png图片,且不能超过10MB
                    </div>
                  </el-upload>
                </template>
              </el-table-column>
              <el-table-column label="头像" align="center">
                <template v-slot="scope">
                  <el-image v-if="scope.row.userPic" :src="scope.row.userPic"
                            style="width: 50px; height: 50px; border-radius: 50px; "
                            :preview-src-list="[scope.row.userPic]"></el-image>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" style="width: 50px;">
                <template slot-scope="scope">
                  <div>
                    <el-button size="mini" type="danger" @click="delById(scope.row)" plain
                               v-if="user.role === '管理员'">删除
                    </el-button>
                  </div>

                  <el-button type="primary"
                             size="mini"
                             @click="updateById(scope.row)"
                             plain>编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <template>
              <div class="block">
                <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page.sync="pageUserReq.pageNum"
                  :page-size="pageUserReq.pageSize"
                  layout="total, prev, pager, next"
                  :total="total">
                </el-pagination>
              </div>
            </template>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import {saveAs} from 'file-saver'
import {Loading, Message} from "element-ui";
import qs from "qs";

export default {
  data() {
    return {
      user: JSON.parse(sessionStorage.getItem('user-key' || '{}')),
      url: '',
      oldUser: {
        id: '',
        username: '',
        nickname: '',
        email: '',
        role: '',
      },
      newUser: {
        username: '',
        nickname: '',
        email: '',
        role: '用户',
      },
      tableData: [],
      loading: true,
      update: false,
      add: false,
      delete: false,
      formLabelWidth: '120px',
      // 弹出层标题
      title: "",
      // 添加数据对话框是否展示的标记
      rules2: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        nickname: [
          {
            required: true,
            message: '请输入昵称',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入电子邮箱',
            trigger: 'blur'
          }
        ],
        role: [
          {
            required: true,
            message: '请输入角色',
            trigger: 'blur'
          }
        ],
      },
      pageUserReq: {
        pageNum: 1,
        pageSize: 3,
        username: '',
        nickname: ''
      },
      total: 0,
      imageUrl: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictType: undefined,
        dictLabel: undefined,
        status: undefined
      },
      dialogVisible: false,
      showFileName: false,
      operationType: '',
      ids: []
    }
  },
  mounted() {//页面加载后触发
    this.fetchData()
  }
  ,
  methods: {
    beforeFileUpload(file) {
      // 检查文件是否存在
      if (!file) {
        this.$message.error('请选择要上传的文件！');
        return false; // 阻止文件上传
      }
      // 检查文件类型和大小（这里只是示例，你可能需要更复杂的逻辑）
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isJPGorPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
        return false;
      }
      // 如果通过检查，则返回 true 表示可以继续上传
      return true;
    },
    handleTableFileUpload(row, file) {
      row.userPic = file.response.data
      // 触发更新
      this.$request.put('/user/updateInfo', row).then(res => {
        if (res.code === 200) {
          this.$message.success("上传成功")
          // 更新浏览器缓存里的用户信息
          this.user.userPic = res.data.userPic
          this.fetchData()
          sessionStorage.setItem('user-key', JSON.stringify(this.user))
          //触发父级的数据更新
          this.$emit('updateUser', this.user)
        } else {
          this.$message.success(res.msg)
        }
      })
    }
    ,
    delById(row) {
      this.$confirm("您确认删除吗？", "确认", {type: "warning"}).then(() => {
        this.$request.delete('/user/deleteById', {params: {id: row.id}}).then(res => {
          if (res.code === 200) {
            this.$message.success("已删除")
            this.fetchData()
            //触发父级的数据更新
            this.$emit('updateUser', this.user)
          } else {
            this.$message.error(res.msg)
          }
        }).catch(() => {
          this.$message.error("系统错误")
        })
      }).catch(() => {
      })
    }
    ,
    updateById(row) {
      this.update = true
      this.oldUser.id = row.id
      this.oldUser.username = row.username
      this.oldUser.nickname = row.nickname
      this.oldUser.email = row.email
      this.oldUser.role = row.role
    },
    handleUpdate() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$request.put('/user/updateInfo', this.oldUser).then(res => {
            if (res.code === 200) {
              //成功更新
              this.fetchData()
              this.update = false
            } else {
              this.$message.error(res.msg)
              this.update = false
            }
            if (this.user.id === JSON.parse(sessionStorage.getItem('user-key' || '{}')).id) {
              sessionStorage.setItem('user-key', JSON.stringify(this.user))
              // 触发父级的数据更新
              this.$emit('updateUser', this.user)
            }
          }).catch(() => {
            this.$message.warning("系统异常")
          })
        }
      })
    },
    handleAdd() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$request.post('/user/addUser', this.newUser).then(res => {
            if (res.code === 200) {
              //成功添加
              this.add = false
              this.fetchData()
              this.newUser.username = ''
              this.newUser.nickname = ''
              this.newUser.email = ''
            } else {
              this.$message.error(res.msg)
              this.add = false
            }
          }).catch(() => {
            this.add = false
            this.$message.error("系统错误")
          })
        }
      })
    },
    fetchData() {
      this.$request.post('/user/userPage', this.pageUserReq).then(res => {
        if (res.code === 200) {
          this.loading = false
          this.tableData = res.data.user;
          this.pageUserReq.pageNum = res.data.pageNum;
          this.pageUserReq.pageSize = res.data.pageSize;
          this.total = res.data.total;
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        // 添加错误处理逻辑
        this.loading = false;
        this.$message.error("系统错误")
      });
    },
    handleSizeChange(val) {
      this.pageUserReq.pageSize = val;
      this.fetchData(); // 当每页显示条数改变时，重新获取数据
    },
    handleCurrentChange(val) {
      this.pageUserReq.pageNum = val;
      this.fetchData(); // 当页码改变时，重新获取数据
    },
    exportUser() {

      let downloadLoadingInstance = Loading.service({

        text: "正在下载数据，请稍候",

        spinner: "el-icon-loading",

        background: "rgba(0, 0, 0, 0.7)"

      });


      this.$request.post('user/export', qs.stringify(this.queryParams), { // 使用 qs 库来转换 params 到 application/x-www-form-urlencoded 格式

        headers: {'Content-Type': 'application/x-www-form-urlencoded'},

        responseType: 'blob'

      })

        .then(async (response) => {

          try {

            const blob = new Blob([response.data])

            saveAs(blob, `log_${new Date().getTime()}.xlsx`);

          } catch (error) {

            console.error(error);

            Message.error('数据处理失败，请稍后重试！');

          } finally {

            downloadLoadingInstance.close();

          }

        })

        .catch((error) => {

          console.error(error);

          Message.error('下载文件出现错误，请联系管理员！');

          downloadLoadingInstance.close();

        });

    },
    reset() {
      this.pageUserReq.username = ""
      this.pageUserReq.nickname = ""
      this.fetchData()
    },
    sercah(pageNum) {
      if (pageNum) {
        this.pageUserReq.pageNum = pageNum
      }
      this.fetchData();
    },
    handleSelectionChange(rows) {
      this.ids = rows.map(v => v.id)
    },
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning("请选中数据")
        return
      }
      this.$confirm("您确认数据批量删除吗？", "确认", {type: "warning"}).then(() => {
        this.$request.delete('/user/deleteByIds', {data: this.ids}).then(res => {
          if (res.code === 200) {
            this.$message.success("已删除")
            this.fetchData()
            //触发父级的数据更新
            this.$emit('updateUser', this.user)
          } else {
            this.$message.error(res.msg)
          }
        }).catch(() => {
          this.$message.error("系统错误")
        })
      }).catch(() => {
      })
    },
    exportData() { // 导出数据
      if (!this.ids.length) { // 全部导出
        window.open('http://localhost:9090/onlineBlog/user/export?token=' + this.user.token +
          "&username=" + this.pageUserReq.username + "&nickname=" + this.pageUserReq.nickname)
      } else {
        let idsStr = this.ids.join(',')
        window.open('http://localhost:9090/onlineBlog/user/export?token=' + this.user.token +
          '&ids=' + idsStr)
      }
    },
    handleImport(res) {
      if (res.code === 200) {
        this.$message.success("操作成功")
      } else {
        this.$message.warning(res.msg)
      }
    },
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
